package Presenter;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import Models.ATCust;
import Models.AllocationTemplate;

public class AllocationTemplatePresenter extends AbstractPresenter<AllocationTemplate> {
	final String SINGLEITEM = "allocationTemplate";
	final String MULTIITEM = "allocationTemplates";
	
	public ArrayList<AllocationTemplate> tryJSONParseArray(String input){
		return super.doJSONParseArray(input, SINGLEITEM, MULTIITEM);
	}
	
	public AllocationTemplate tryJSONParse(String input){
		return super.doJSONParse(input, SINGLEITEM);
	}
	
	public AllocationTemplate createItemFromJSONObject(JSONObject jsonObject){
		AllocationTemplate item = new AllocationTemplate();
		try{
			item.setaTempDesc(jsonObject.getString("ATDesc"));
			item.setaTempID(jsonObject.getInt("atid"));
			item.setcGroupID(jsonObject.getInt("ATCGroup"));
			item.setRepCount(jsonObject.getInt("repCount"));
			item.setRepType(jsonObject.getInt("repType"));
			
			//Set LabType Collection
			ArrayList<ATCust> customers = new ArrayList<ATCust>();
			if(!jsonObject.isNull("atCustCollection")){
				Object itm = jsonObject.get("atCustCollection");
				ATCustPresenter presenter = new ATCustPresenter();
				if(itm instanceof JSONArray){
					JSONArray jPSTArray = (JSONArray)itm;
					for(int i=0; i<jPSTArray.length(); i++){
						JSONObject jsonItem = jPSTArray.getJSONObject(i);
						customers.add(presenter.createItemFromJSONObject(jsonItem));
					}
				} else {
					JSONObject jsonItem = (JSONObject)itm;
					customers.add(presenter.createItemFromJSONObject(jsonItem));
				}
				item.setCustomerTemplates(customers);
			}
			
			return item;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(AllocationTemplate item){
		try{
			JSONObject json = new JSONObject();
			json.put("ATDesc", item.getaTempDesc());
			json.put("atid", item.getaTempID());
			json.put("ATCGroup", item.getcGroupID());
			json.put("repCount", item.getRepCount());
			json.put("repType", item.getRepType());
			
			//Create Beers Collection
			if(item.getCustomerTemplates()!=null){
				ATCustPresenter presenter = new ATCustPresenter();
				if(item.getCustomerTemplates().size()>0){
					JSONArray jsonArray = new JSONArray();
					for(int i=0; i<item.getCustomerTemplates().size(); i++){
						jsonArray.put(presenter.createJSON(item.getCustomerTemplates().get(i)));
					}
					json.put("atCustCollection", jsonArray);
				}
			}
			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public AllocationTemplate getEmptyEntity(){
		AllocationTemplate entity = new AllocationTemplate();
		return entity;
	}
}
